import { UserConfig, ConfigEnv, loadEnv } from 'vite';
import { createVitePlugins } from './config/vite/plugins';
import { resolve } from 'path';
import proxy from './config/vite/proxy';
import { VITE_PORT } from './config/constant';
import postCssPxToRem from 'postcss-pxtorem';
function pathResolve(dir: string) {
    return resolve(process.cwd(), '.', dir);
}

// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfig => {
    const isBuild = command === 'build';
    let base: string;
    if (command === 'build') {
        base = '/';
    } else {
        base = '/';
    }
    return {
        base,
        resolve: {
            alias: [
                // @/xxxx => src/xxxx
                {
                    find: /\@\//,
                    replacement: pathResolve('src') + '/'
                },
                // #/xxxx => types/xxxx
                {
                    find: /\#\//,
                    replacement: pathResolve('types') + '/'
                },
                // c/xxxx => types/xxxx
                {
                    find: /\_c\//,
                    replacement: pathResolve('config') + '/'
                }
            ]
        },
        // plugins
        plugins: createVitePlugins(isBuild, mode),

        build: {
            minify: 'terser',
            terserOptions: {
                compress: {
                    //生产环境时移除console.log()
                    drop_console:
                        loadEnv(mode, process.cwd())['VITE_BUILD_DROP_CONSOLE'] === 'true',
                    drop_debugger:
                        loadEnv(mode, process.cwd())['VITE_BUILD_DROP_CONSOLE'] === 'true'
                },
                sourceMap: loadEnv(mode, process.cwd())['VITE_BUILD_SOURCEMAP'] === 'true'
            }
        },
        // css
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: `@import "@/styles/variables.module.scss"; @import "@/styles/mixins.scss";`
                }
            },
            postcss: {
                plugins: [
                    postCssPxToRem({
                        rootValue: 16,
                        propList: ['*'], // 需要转换的属性，这里选择全部都进行转换
                        exclude: '/node_modules|thematic-research/i'
                    })
                ]
            }
        },
        // server
        server: {
            hmr: { overlay: false }, // 禁用或配置 HMR 连接 设置 server.hmr.overlay 为 false 可以禁用服务器错误遮罩层
            // 服务配置
            port: VITE_PORT, // 类型： number 指定服务器端口;
            open: false, // 类型： boolean | string在服务器启动时自动在浏览器中打开应用程序；
            cors: false, // 类型： boolean | CorsOptions 为开发服务器配置 CORS。默认启用并允许任何源
            host: '0.0.0.0', // IP配置，支持从IP启动
            proxy
        }
    };
};
